package com.migration.model.migration;

import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多线程迁移脚本抽象类
 * 为多线程迁移脚本提供通用方法和属性
 */
public abstract class AbstractMultiThreadMigrationScript extends AbstractMigrationScript {

    /**
     * 线程池大小
     * 默认值为5
     */
    @Value("${migration.thread.pool.size:5}")
    protected int threadPoolSize;
    
    /**
     * 批处理大小
     * 默认值为1000
     */
    @Value("${migration.batch.size:1000}")
    protected int batchSize;
    
    /**
     * 构造函数
     * 
     * @param name 迁移名称
     * @param description 迁移描述
     * @param sourceTable 源表名
     * @param targetTable 目标表名
     * @param order 执行顺序
     */
    protected AbstractMultiThreadMigrationScript(String name, String description, String sourceTable, String targetTable, Integer order) {
        super(name, description, sourceTable, targetTable, order);
    }
    
    /**
     * 创建线程池
     * 
     * @return 线程池
     */
    protected ExecutorService createExecutorService() {
        return Executors.newFixedThreadPool(threadPoolSize);
    }
    
    /**
     * 创建并发计数器
     * 
     * @param count 计数器初始值
     * @return 计数器
     */
    protected CountDownLatch createCountDownLatch(int count) {
        return new CountDownLatch(count);
    }
    
    /**
     * 创建原子计数器
     * 
     * @return 原子计数器
     */
    protected AtomicInteger createAtomicCounter() {
        return new AtomicInteger(0);
    }
    
    /**
     * 计算批次数
     * 
     * @param dataSize 数据总量
     * @return 批次数
     */
    protected int calculateBatchCount(int dataSize) {
        return (int) Math.ceil((double) dataSize / batchSize);
    }
    
    /**
     * 等待所有任务完成
     * 
     * @param latch 计数器
     * @param executorService 线程池
     */
    protected void waitForCompletion(CountDownLatch latch, ExecutorService executorService) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            executorService.shutdown();
        }
    }
    
    /**
     * 等待特定数量的任务完成
     * 
     * @param latch 计数器
     * @param remainingTasks 剩余任务数
     */
    protected void waitForPartialCompletion(CountDownLatch latch, int remainingTasks) {
        try {
            while (latch.getCount() > remainingTasks) {
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
} 